import Cookies from 'js-cookie'
if (!window.longmao) window.longmao = {};
export const longmao = window.longmao
    //  私有变量
let dev = /^dev.+$/.test(window.document.domain) ? 'dev.' : '';
let offline = /^offline.+$/.test(document.domain) ? 'offline.' : '';
let prefix = offline != '' ? offline : dev
let apis = {
    validate: `http://${prefix}128.196.150.85:1350/v1/api/unsafe/system/auth/token/validate`,
    refresh: `http://${prefix}128.196.150.85:1350/v1/api/unsafe/system/auth/token/refresh`,
    destroy: `http://${prefix}128.196.150.85:1350/v1/api/unsafe/system/auth/token/destroy`,
    jump: `http://${prefix}128.196.150.85:1350/v1/api/safe/system/auth/login/jump/make`,
    token: `http://${prefix}128.196.150.85:1350/v1/api/unsafe/system/auth/password/login`,
    userinfo: `http://${prefix}128.196.150.85:1350/v1/api/safe/system/auth/user/info`,
    login: `http://${prefix}128.196.150:86:1345?referer=${location.origin}`
};

// 私有方法
let storage = {
    getToken: function() {
        console.log(Cookies.get('token', { path: '/', domain: 'longmaosoft.com' }));
        if (Cookies.get('token', { path: '/', domain: 'longmaosoft.com' }) != undefined) {
            return Cookies.get('token', { path: '/', domain: 'longmaosoft.com' });
        }
        return null;
        /* return localStorage.getItem('token'); */
    },
    setToken: function(value) {
        localStorage.setItem('token', value);
    },
    deleteToken: function() {
        localStorage.removeItem('token');
    }
};

function ajax(url, token) {
    let xhr = new XMLHttpRequest();
    return new Promise((resolve, reject) => {
        xhr.open('POST', url);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                let resData = JSON.parse(xhr.responseText)
                if (xhr.status === 200) {
                    resolve(resData);
                } else {
                    reject(new Error('网络连接超时'))
                }
            }
        };
        if (token) {
            xhr.setRequestHeader('Token', token);
        }
        xhr.send()
    })
}

function getNewToken(token) {
    return new Promise((resolve, reject) => {
        ajax(apis.token, token).then((data) => {
            if (data.code == '200') {
                resolve(data.object)
            } else {
                reject(data)
            }
        }).catch((err) => {
            reject(err)
        })
    })
}

function validateToken(token) {
    return new Promise((resolve, reject) => {
        if (token) { //如果URL中存在Token，则先校验URL, Token
            ajax(apis.validate, token).then((data) => {
                if (data.code == '200' || data.code == '202') {
                    resolve(data.object);
                } else {
                    token = storage.getToken();
                    if (!token) {
                        reject({ code: '401', message: '登录超时' });
                        return;
                    }

                    ajax(apis.validate, token).then((data) => {
                        if (data.code == '200' || data.code == '202') {
                            resolve(data.object);
                        } else {
                            reject(data);
                        }
                    }).catch((err) => {
                        reject(err)
                    })
                }
            });
        } else {
            token = storage.getToken();
            if (!token) {
                reject({ code: '401', message: '登录超时' });
                return;
            }

            ajax(apis.validate, token).then((data) => {
                if (data.code == '200') {
                    resolve(data.object);
                } else {
                    reject(data);
                }
            }).catch((err) => {
                reject(err)
            })
        }
    });
}

function refreshToken(token) {
    return new Promise((resolve, reject) => {
        ajax(apis.refresh, token).then((data) => {
            if (data.code == '200') {
                storage.setToken(data.object.token);
                resolve(data)
            } else {
                reject(data)
            }

        }).catch((err) => {
            reject(err)
        })
    })
}

function refreshTokenInterval(data) {
    setTimeout(() => {
        refreshToken(data.token).then((data) => {
            if (data.code == '200') {
                refreshTokenInterval(data.object)
            }
        })
    }, (data.refresh / 2) * 1000);
}

function getUserinfo(token) {
    return new Promise((resolve, reject) => {
        ajax(apis.userinfo, token).then((data) => {
            if (data.code == 200) {
                resolve(data)
            } else {
                reject(data)
            }

        }).catch((err) => {
            reject(err)
        })
    })
}

//  静态方法(外部调用)
longmao.sso = {
    getToken: function() {
        return new Promise((resolve, reject) => {
            let token = storage.getToken();
            return getNewToken(token).then((data) => {
                storage.setToken(data.token);
                resolve();
            }).catch((data => {
                reject(data);
            }));
        });
    },
    check: function() {
        let reg = new RegExp("(\\?|&)token=([^&]+)"); //构造一个含有目标参数的正则表达式对象
        let r = window.location.search.match(reg); //匹配目标参数
        let token;
        if (r != null) {
            token = decodeURI(r[2]) // 返回参数
        }

        return new Promise((resolve, reject) => {
            validateToken(token).then((data) => {
                storage.setToken(data.token);
                refreshTokenInterval(data);
                resolve(data);
            }).catch((data) => {
                reject(data);
            });
        });
    },
    jump: function(url) {
        return new Promise((resolve, reject) => {
            if (url.indexOf('?') > 0) {
                url += '&';
            } else {
                url += '?';
            }
            let token = storage.getToken();
            ajax(apis.jump, token).then((data) => {
                if (data.code == '200') {
                    resolve(`${url}token=${data.object.token}`);
                } else {
                    reject(data);
                }
            }).catch((err) => {
                reject(err);
            })
        })
    },
    getInfo: function() {
        return new Promise((resolve, reject) => {
            let token = storage.getToken();
            return getUserinfo(token).then((data) => {
                resolve(data);
            }).catch((data => {
                reject(data);
            }));
        });
    },
    logout: function() {
        return new Promise((resolve, reject) => {
            let token = storage.getToken();
            ajax(apis.destroy, token).then((data) => {
                if (data.code == '200') {
                    Cookies.remove('token', { path: '/', domain: 'longmaosoft.com' });
                    resolve();
                } else {
                    reject(data);
                }
            }).catch((err) => {
                reject(err);
            })
        });
        storage
    },
    login: function() {
        storage.deleteToken();
        window.location = apis.login;
    },
    token: function() {
        return storage.getToken();
    }
};